/**
 * Created by user on 2015/9/23.
 */


var async = require('async');
var moment = require('moment');
var mysqlUtil = require('../../../common/utils/mysqlUtil');
var Goods = mongoose.model('goods');
var GoodsReply = mongoose.model('goods_reply');
var GoodsQueryTerms = mongoose.model('goods_queryTerms');
var GoodsCategory = mongoose.model('goods_category');
var Community = mongoose.model('community');
var User = mongoose.model('user');


exports.secondHandListService = function(req ,callback) {

    var body = req.body;
    var page = req.params.page;
    var size = Number(req.params.size);
    var index = (Number(req.params.page) - 1) * size;
    var totalPage = 0;

    var option =  {isValid:true};
    if (body.city) option.city = body.city;
    if (body.community) option.community = body.community;
    if (body.createdBy) option.createdBy = body.createdBy;
    if (body.category) option.category = body.category;
    if (body.level) option.level = Number(body.level);
    if (body.dealStatus) option.dealStatus = Number(body.dealStatus);
    if (body.title) option.title = new RegExp(body.title);

    if(body.sale =='1'){
        option.saleNumber = { '$exists': true };
    }else if(body.sale =='0'){
        option.saleNumber = { '$exists': false }
    };

    if (body.floorPrice || body.topPrice) {
        if (body.floorPrice && body.topPrice) {
            if (body.floorPrice <= body.topPrice) {
                option.presentPrice = {$gte: body.floorPrice, $lte: body.topPrice};
            }
        } else if (body.floorPrice) {
            option.presentPrice = {$gte: body.floorPrice};
        } else if (body.topPrice) {
            option.presentPrice = {$lte: body.topPrice};
        };
    };

    if (body.startDate || body.endDate) {
        if (body.startDate && body.endDate) {
            if (body.startDate < body.endDate) {
                option.releaseDate = {$gte: body.startDate, $lte: body.endDate};
            }
        } else if (body.startDate) {
            option.releaseDate = {$gte: body.startDate};
        } else if (body.endDate) {
            option.releaseDate = {$lte: body.endDate};
        };
    };

    if(body.itemType) {
        option.itemType = parseInt(body.itemType);
    }

    var sortType = {releaseDate: -1};
    if(body.sort=='1'){
        sortType = {presentPrice : -1}
    };
    if(body.sort=='2'){
        sortType = {presentPrice : 1}
    };


    //logger.debug('body:');
    logger.debug(body);
    logger.debug(sortType);

    async.series([

        function (callbackInner) {

            if (body.nickName || body.phone) {
                var opt ={};
                //if (body.nickName) opt.nickName = new RegExp(body.nickName);
                //if (body.phone) opt.mobilePhone = new RegExp(body.phone);
                if (body.nickName) opt.nickName = body.nickName;
                if (body.phone) opt.mobilePhone = body.phone;

                logger.debug(opt);
                User.find(opt, function (err, result) {
                    logger.debug(result.length);
                    option.createdBy = {$in:result};
                    callbackInner(err, result);
                });
            }else {
                callbackInner();
            }
        },

        function (callbackInner) {
            Goods.count(option, function (err, count) {
                //logger.debug(count);
                totalPage = Math.ceil(count/size);
                var temp = {count: count, totalPage:totalPage};
                callbackInner(err, temp);

            });
        },

        function (callbackInner) {
            logger.debug(option);
            Goods.find(option)
                .populate('community', 'communityName')
                .populate('aroundCommunity', '_id communityName')
                .populate('city', 'name')
                .populate('createdBy', '_id nickName mobilePhone dateCreated')
                .populate('category', 'name itemType')
                .sort(sortType).skip(index).limit(size).exec(function (err, result) {

                    async.eachSeries(result, function (goods, callbackInner2) {
                        for(img in goods.images) {
                            goods.images[img].imageURL = 'http://' + imgHost + goods.images[img].imageURL;
                        };

                        var key = "goods:" + goods._id + ":detail";
                        var opt = [
                            key,
                            'browner',
                            'replyCount',
                            'collectionNum'
                        ];
                        redisClient.hmget(opt, function (err, result) {
                            goods._doc.browner = result[0] == null ? 0 : result[0];
                            goods._doc.replyCount = result[1] == null ? 0 : result[1];
                            goods._doc.collectionNum = result[2] == null ? 0 : result[2];
                            callbackInner2(err, goods)
                        });


                    }, function (err) {
                        callbackInner(err,result);
                    });

                    //callbackInner(err, result);
                });
        }
    ], callback);

};

exports.getGoodsCategoryService = function(req ,callback) {

    GoodsCategory.find(null).sort({itemType:1}).exec(function (err, results) {
        if (results != null) {
            callback(null, results);
        } else {
            var msg = {
                "message": 'No such GoodsCategory'
            }
            callback(msg, null);
        }
    });

}

exports.deleteSecondHandService = function(req ,callback) {

    var ids = req.body.secondHandID;
    //if (!id)  return callback('body错误', null);

    //Goods.update({_id:id}, {isValid: false}, callback);

    //var queryIn = {};
    //queryIn["$in"] = [];
    //for (var i = 0, l = ids.length; i < l; i++) {
    //    queryIn["$in"].push(ids[i]);
    //}
    //logger.debug(queryIn);
    ////banner.remove({_id :queryUserIn}, callback);
    //Goods.update({_id:queryIn}, {isValid: false},{ multi: true }, callback);

    async.eachSeries(ids, function (id, callbackInner) {
        logger.debug(id);

        restClient.delete('http://' + AppHost + '/rest/v1.0/backoffice/delGoods/' + id, function (data, response) {

            callbackInner();
        });

    }, function (err) {
        callback(err, null);
    });

};

exports.updateSecondHandService = function(req ,callback) {

    var id = req.body.id;
    var secondHand = req.body.secondHand;
    if (!(id && secondHand))  return callback('body错误', null);
    secondHand.isInit = 1;
    logger.debug(secondHand);
    Goods.update({_id:id}, secondHand, callback);
};

exports.getReplyListService = function (req, callback) {

    var goodsId = req.body.goodsId;

    GoodsReply.find({goodsId: goodsId}).populate('community', '_id communityName communityAddress')
        .populate('repliedBy', 'userName email mobilePhone nickName')
        .populate('goodsId', 'title desc images presentPrice originalPrice')
        .exec(function (err, results) {
            if (err) {
                return callback(err);
            } else {
                return callback(null, results);
            }
        });
};


exports.exportSecondHandService = function(req ,callback) {

    var body = req.cparams;
    //var page = req.params.page;
    //var size = Number(req.params.size);
    //var index = (Number(req.params.page) - 1) * size;
    //var totalPage = 0;

    var option =  {isValid:true};
    if (body.city) option.city = body.city;
    if (body.community) option.community = body.community;
    if (body.createdBy) option.createdBy = body.createdBy;
    if (body.category) option.category = body.category;
    if (body.level) option.level = Number(body.level);
    if (body.dealStatus) option.dealStatus = Number(body.dealStatus);
    if (body.title) option.title = new RegExp(body.title);

    if(body.sale =='1'){
        option.saleNumber = { '$exists': true };
    }else if(body.sale =='0'){
        option.saleNumber = { '$exists': false }
    };

    if (body.floorPrice || body.topPrice) {
        if (body.floorPrice && body.topPrice) {
            if (body.floorPrice < body.topPrice) {
                option.presentPrice = {$gte: body.floorPrice, $lte: body.topPrice};
            }
        } else if (body.floorPrice) {
            option.presentPrice = {$gte: body.floorPrice};
        } else if (body.topPrice) {
            option.presentPrice = {$lte: body.topPrice};
        };
    };

    if (body.startDate || body.endDate) {
        if (body.startDate && body.endDate) {
            if (decodeURI(body.startDate) < decodeURI(body.endDate)) {
                option.releaseDate = {$gte: decodeURI(body.startDate), $lte: decodeURI(body.endDate)};
            }
        } else if (body.startDate) {
            option.releaseDate = {$gte: decodeURI(body.startDate)};
        } else if (body.endDate) {
            option.releaseDate = {$lte: decodeURI(body.endDate)};
        };
    };

    var sortType = {releaseDate: -1};
    if(body.sort=='1'){
        sortType = {presentPrice : -1}
    };
    if(body.sort=='2'){
        sortType = {presentPrice : 1}
    };

    logger.debug('body:');
    logger.debug(body);
    logger.debug(sortType);

    async.series([

        function (callbackInner) {

            if (body.nickName || body.phone) {
                var opt ={};
                //if (body.nickName) opt.nickName = new RegExp(body.nickName);
                //if (body.phone) opt.mobilePhone = new RegExp(body.phone);
                if (body.nickName) opt.nickName = body.nickName;
                if (body.phone) opt.mobilePhone = body.phone;

                logger.debug(opt);
                User.find(opt, function (err, result) {
                    logger.debug(result.length);
                    option.createdBy = {$in:result};
                    callbackInner(err, result);
                });
            }else {
                callbackInner();
            }
        },

        function (callbackInner) {
            logger.debug(option);
            Goods.find(option)
                .populate('community', 'communityName')
                //.populate('aroundCommunity', '_id communityName')
                .populate('city', 'name')
                .populate('createdBy', '_id nickName mobilePhone dateCreated')
                .populate('category', 'name')
                .sort(sortType)
                //.sort(sortType).skip(index).limit(size)
                .exec(function (err, result) {

                    async.eachSeries(result, function (goods, callbackInner2) {
                        for(img in goods.images) {
                            goods.images[img].imageURL = 'http://' + imgHost + goods.images[img].imageURL;
                        };

                        var key = "goods:" + goods._id + ":detail";
                        var opt = [
                            key,
                            'browner',
                            'replyCount',
                            'collectionNum'
                        ];
                        redisClient.hmget(opt, function (err, result) {
                            goods._doc.browner = result[0] == null ? 0 : result[0];
                            goods._doc.replyCount = result[1] == null ? 0 : result[1];
                            goods._doc.collectionNum = result[2] == null ? 0 : result[2];
                            callbackInner2(err, goods)
                        });


                    }, function (err) {
                        callbackInner(err,result);
                    });

                });
        }
    ], callback);

};


exports.handleLevelService = function(req ,callback) {

    var body = req.body;

    logger.debug(body);
    if (!body.id)  return callback('body错误', null);

    var data = {level:body.level};

    if(body.level==1){
        data.recDate = moment();
    };
    //logger.debug(data);
    Goods.update({_id:body.id}, data, callback);
};

exports.handleSaleService = function(req ,callback) {

    var body = req.body;

    logger.debug(body);
    if (!body.id)  return callback('body错误', null);

    Goods.update({_id:body.id}, {$unset:{saleNumber:-1}}, callback);
};

exports.secondHandReplyListService = function (req, callback) {

    //var body = req.body;
    //var page = req.params.page;
    var size = Number(req.params.size);
    var index = (Number(req.params.page) - 1) * size;

    var replyBy = req.body.replyBy;

    async.series([

        function (callbackInner) {
            GoodsReply.count({repliedBy: replyBy}, function (err, count) {

                if (err) {
                    callbackInner(err, null);
                }else {
                    var temp = {count: count, totalPage:Math.ceil(count/size)};
                    callbackInner(err, temp);
                }
            });
        },
        function (callbackInner) {

            GoodsReply.find({repliedBy: replyBy}).sort({dateReplied:-1}).skip(index).limit(size)
                .populate('community', '_id communityName communityAddress')
                .populate('repliedBy', 'userName email mobilePhone nickName')
                .populate('goodsId', 'title desc images presentPrice originalPrice')
                .exec(function (err, results) {

                    //logger.debug(results);

                    if (err) {
                        return callbackInner(err);
                    } else {
                        return callbackInner(null, results);
                    }
                });

        }

    ], callback);


};

exports.deleteSecondHandReplyService = function (req ,callback) {

    var body = req.body;

    GoodsReply.remove({_id: body.replyId}, callback);

};

